import {
  Button,
  Input,
  List,
  Modal,
  Pagination,
  Popconfirm,
  Space,
  Typography,
} from "antd";
import styles from "./Memo.module.css";
import { memo, useEffect, useState } from "react";
import { copyText } from "../../../../utils/common/copy";
import { toast } from "../../../../components/Toast/Toast";
import React from "react";
import { clipboardApi, memoApi } from "../../../../utils/backend/server";
import { useAppDispatch, useAppSelector } from "../../../../utils/store/hooks";
import { fetchMemoList } from "../../../../utils/store/MemoSlice";
import { fetchClipboard } from "../../../../utils/store/clipboardSlice";

export interface MemoItem {
  id: string;
  content: string;
  seq: number;
}

export const addMemo = async (val: string) => {
  return memoApi.addMemo({
    id: "",
    content: val,
    seq: 0,
  });
};

const MemoHead = (props: {
  refresh: () => void;
  setList: (data: MemoItem[]) => any;
}) => {
  const [val, setVal] = useState<string>("");

  const add = async (): Promise<void> => {
    const newList = await addMemo(val);
    toast("add new memo");
    props.setList(newList);
    setVal("");
  };
  return (
    <div className={styles.entry}>
      <Input
        autoFocus
        onChange={(e) => setVal(e.target.value)}
        value={val}
        onKeyDown={(e) => {
          if (e.key !== "Enter") return;
          add();
        }}
      />

      <div className={styles.opt}>
        <span onClick={add}>+</span>
        <span onClick={props.refresh}>refresh</span>
      </div>
    </div>
  );
};
// list: MemoItem[];
// setList: (data: MemoItem[]) => void;
// refresh: () => Promise<any>;
const ContextMenu = (props: {
  show: boolean;
  item: MemoItem;
  index: number;
  close: () => void;
}) => {
  const dispatch = useAppDispatch();
  const pop = async (item: MemoItem) => {
    try {
      const memo = await memoApi.getMemoById(item.id);
      await clipboardApi.setClipboard(memo.content);
      await memoApi.removeMemo(item.id);
      // await props.refresh();
      dispatch(fetchClipboard());
      dispatch(fetchMemoList({}));
      props.close();
      toast("pop success!");
    } catch (err) {
      toast("pop failed!");
      console.log(err);
    }
  };

  const copy = async (item: MemoItem) => {
    const data = await memoApi.getMemoById(item.id);
    await copyText(data.content);
    toast("copied!");
  };

  return (
    <Modal title="operations..." open={props.show} onCancel={props.close}>
      <div className={styles.opt}>
        <Space
          onClick={(e) => {
            e.stopPropagation();
          }}
        >
          <Button type="primary" onClick={() => copy(props.item)}>
            Copy
          </Button>
          <Button type="primary" onClick={() => pop(props.item)}>
            Pop
          </Button>
          {/* {props.index > 0 ? (
            <Button
              onClick={() => {
                // props.exchangeSeq(props.index, true, props.list, props.setList)
              }}
            >
              <CaretUpOutlined />
            </Button>
          ) : (
            <></>
          )}
          {props.index < props.list.length - 1 ? (
            <Button
              onClick={() => {
                // props.exchangeSeq(props.index, false, props.list, props.setList)
              }}
            >
              <CaretDownOutlined />
            </Button>
          ) : (
            <></>
          )} */}
          <Popconfirm
            title="Delete the memo?"
            description="Are you sure to delete this memo?"
            okText="Yes"
            cancelText="No"
            onConfirm={(e) => {
              memoApi.removeMemo(props.item.id).then((data) => {
                toast("remove memo");
                // props.setList(data);
                dispatch(fetchMemoList({}));
                props.close();
              });
            }}
          >
            <Button danger type="primary">
              delete
            </Button>
          </Popconfirm>
        </Space>
      </div>
    </Modal>
  );
};

// type ExchangeSeqType = (
//   index: number,
//   up: boolean,
//   list: MemoItem[],
//   setList: (data: MemoItem[]) => any
// ) => void;
//   setList: (data: MemoItem[]) => any;
//   refresh: () => Promise<any>;
//   list: MemoItem[];
// props: { exchangeSeq: ExchangeSeqType }
export const MemoList = () => {
  const memo = useAppSelector((state) => state.memo);
  const dispatch = useAppDispatch();
  const [chosen, setChosen] = useState<{
    item: MemoItem;
    index: number;
    show: boolean;
  }>({
    item: { id: "", content: "", seq: -1 },
    index: -1,
    show: false,
  });

  return (
    <div className={styles.listBox}>
      {/* <div className={styles.list}>{list.map((val) => val)}</div> */}
      <List
        dataSource={memo.list}
        renderItem={(item, index) => (
          <List.Item
            className={styles.item}
            // onClick={() => {
            //   copyText(item.content).then(() => {
            //     toast("message copied!");
            //   });
            // }}
            onClick={() =>
              setChosen({
                item,
                index,
                show: true,
              })
            }
          >
            <div>
              <Typography.Text mark>[EVENT]:</Typography.Text>
            </div>
            <div className={styles.itemText}>{item.content}</div>
          </List.Item>
        )}
        header={<div>Memo ({memo.total})</div>}
      />
      <Pagination
        defaultCurrent={1}
        total={memo.total}
        pageSize={memo.pageSize}
        current={memo.pageNo}
        onChange={(pageNo) => {
          dispatch(
            fetchMemoList({
              ...memo,
              pageNo,
            })
          );
        }}
      />
      {/* 
        list={props.list}
        setList={props.setList}
        refresh={props.refresh}
        exchangeSeq={props.exchangeSeq}
      */}
      <ContextMenu
        show={chosen.show}
        item={chosen.item as MemoItem}
        index={chosen.index as number}
        close={() => {
          setChosen((e) => ({ ...e, show: false }));
        }}
      />
    </div>
  );
};

// export const exchangeSeq = async (
//   index: number,
//   up: boolean,
//   list: MemoItem[]
//   // setList: (data: MemoItem[]) => any
// ) => {
//   const item1 = list[up ? index - 1 : index + 1];
//   const item2 = list[index];
//   await memoApi.exchangeMemoSeq(item1.id, item2.id);
//   // .then((data) => {
//   //   // setList(data);
//   // });
// };

// export const refreshMemoList = async (setList: (data: MemoItem[]) => any) => {
//   const data = await memoApi.fetchMemoList({});
//   setList(data);
// };

// export const Memo = () => {
//   const dispatch = useAppDispatch();
//   // const [list, setList] = useState<MemoItem[]>([]);
//   const list = useAppSelector((state) => state.memo).list;

//   useEscape();

//   useEffect(() => {
//     // refreshMemoList(setList);
//     dispatch(fetchMemoList({}));
//   }, []);

//   return (
//     <div className={styles.box}>
//       <MemoHead setList={setList} refresh={() => refreshMemoList(setList)} />
//       <MemoList
//         exchangeSeq={exchangeSeq}
//         list={list}
//         setList={setList}
//         refresh={() => refreshMemoList(setList)}
//       />
//     </div>
//   );
// };
